package cn.cyh.org.service.impl;

import cn.cyh.basic.service.impl.BaseServiceImpl;
import cn.cyh.basic.uitls.MD5Utils;
import cn.cyh.basic.uitls.StrUtils;
import cn.cyh.org.domain.Employee;
import cn.cyh.org.mapper.EmployeeMapper;
import cn.cyh.org.service.IEmployeeService;
import cn.cyh.user.domain.LoginInfo;
import cn.cyh.user.mapper.LoginInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


// 支持事务 (如果有事务就加入事务，没有就不加入)
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    //  自动注入
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Override
    public void save(Employee employee) {
        initEmployee(employee);
        LoginInfo loginInfo = employee2LoginInfo(employee);
        loginInfoMapper.save(loginInfo);
        employee.setLogininfo_id(loginInfo.getId());
        employeeMapper.save(employee);
    }

    private LoginInfo employee2LoginInfo(Employee employee) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(employee,loginInfo);
        loginInfo.setType(0);// 设置后端员工
        return loginInfo;
    }


    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        // 加盐加密
        String byMd5 = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(byMd5);
    }

    @Override
    public void update(Employee employee) {
        super.update(employee);
    }

    @Override
    public void remove(Long eid) {
        Employee employee = employeeMapper.loadById(eid);
        loginInfoMapper.remove(employee.getLogininfo_id());
        employeeMapper.remove(eid);
    }
}
